﻿using System;
using Eg.Core;
using log4net.Config;
using NHibernate;

namespace SessionMerge
{

    class Program
    {

        static void Main(string[] args)
        {
            #region NH configuration

            XmlConfigurator.Configure();
            var nhConfig = new ConfigurationBuilder().Build();
            var sessionFactory = nhConfig.BuildSessionFactory();
            Console.WriteLine("NHibernate Configured!");

            #endregion

            var book = CreateAndSaveBook(sessionFactory);

            // book = entity without a session
            // changes to this entity are not being tracked

            book.Name = "Dormice in Action";
            book.Description = "Hibernation of the Hazel Dormouse";
            book.UnitPrice = 0.83M;
            book.ISBN = "0123";

            using (var session = sessionFactory.OpenSession()) {
                using (var tx = session.BeginTransaction()) {
                    var mergedBook = (Book)session.Merge(book);
                    tx.Commit();

                    // Returns false
                    Console.WriteLine("ReferenceEquals(book, mergedBook) = " + ReferenceEquals(book, mergedBook));
                }
            }

            Console.ReadKey();
        }


        private static Book CreateAndSaveBook(ISessionFactory sessionFactory)
        {
            var book = new Book() {
                Name = "NHibernate 3.0 Cookbook",
                Description = "Pure Awesome.",
                UnitPrice = 50.0M,
                ISBN = "3043",
                Author = "Jason Dentler",
            };

            using (var session = sessionFactory.OpenSession()) {
                using (var tx = session.BeginTransaction()) {
                    session.Save(book);
                    tx.Commit();

                    // remove the instance from session cache
                    session.Evict(book);
                }
            }

            return book;
        }


    }
}
